package multdata.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

/**
 * Zoo
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryZoo",
        transactionManagerRef = "transactionManagerZoo",
        basePackages = {"multdata.repository.zoo"})
public class JpaConfigZoo {

    @Autowired
    @Qualifier("dataSourceZoo")
    private DataSource dataSource;
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryZoo(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean emfb =
                builder.dataSource(dataSource).packages("multdata.entity.zoo").build();
//        emfb.setJpaVendorAdapter(jpaVendorAdapter);
        return emfb;
    }

    @Bean
    public EntityManager entityManagerZoo(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryZoo(builder).getObject().createEntityManager();
    }

    @Bean
    PlatformTransactionManager transactionManagerZoo(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryZoo(builder).getObject());
    }
}
